let h = ['d', 'h', 'e', 'b', 'f', 'g', 'c', 'a'];
let z = ['d', 'b', 'h', 'e', 'a', 'f', 'c', 'g'];

function Node(val) {
    this.value = val;
    this.left = null;
    this.right = null;
}

function fn(z, h) {
    if (z == null || h == null || z.length == 0 || h.length == 0 || z.length != h.length) {
        return null;
    }
    const rootNode = h[h.length - 1];
    const root = new Node(rootNode);
    const zIndex = z.indexOf(rootNode);
    const zLeft = z.slice(0, zIndex);
    const zRight = z.slice(zIndex + 1, z.length);
    const hLeft = h.slice(0, zIndex);
    const hRight = h.slice(zIndex, h.length - 1);
    root.left = fn(zLeft, hLeft);
    root.right = fn(zRight, hRight);
    return root;
}

console.log(fn(z,h));